package com.hospital;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hospital.pony.base.BaseActivity;
import com.hospital.pony.config.Consts;
import com.hospital.pony.db.MemberUserUtils;
import com.hospital.pony.model.ResponseEntry;
import com.hospital.pony.model.UserModel;
import com.hospital.pony.util.LoadingDialog;
import com.hospital.pony.util.ToastUtil;

import net.tsz.afinal.http.AjaxParams;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

/**
 * 登录页面
 * 
 * @author WangXuan
 * 
 */

public class LoginActivity extends BaseActivity {
	// title
	private TextView mTvTitle;
	// 登录用户名称
	private EditText mLoginNumber;
	// 登录密码
	private EditText mLoginPswd;
	// 登录按钮
	private Button mLogin;
	private Button mEnterpriseQuery;
	private LinearLayout mllTop;
	private UserModel userModel;

	private CheckBox login_for_pswd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		if(MemberUserUtils.getJIzHuFlag(this).equals("true")&&!TextUtils.isEmpty(MemberUserUtils.getUid(this))){
			LoginUserPost(true);
		}else{
			initWidget();
		}


	}

	/**
	 * 控件初始化
	 */
	@Override
	public void initWidget() {
		login_for_pswd = (CheckBox) findViewById(R.id.login_for_pswd);
		mdialog = new LoadingDialog(this, "正在登录");
		mTvTitle = (TextView) findViewById(R.id.mTvTitle);
		mTvTitle.setText("登录");
		mLoginNumber = (EditText) findViewById(R.id.mLoginNumber);
		mLoginPswd = (EditText) findViewById(R.id.mLoginPswd);
		mLogin = (Button) findViewById(R.id.mLogin);
		mEnterpriseQuery = (Button) findViewById(R.id.mEnterpriseQuery);
		// mLoginNumber.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		// 事件的监听
		mLogin.setOnClickListener(this);
		mEnterpriseQuery.setOnClickListener(this);
		// 给输入框设置默认的测试数据
		mLoginNumber.setSelection(mLoginNumber.getText().length());

		mLoginNumber.setText("15249249900");
		mLoginPswd.setText("123456");

		login_for_pswd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
				if(b){
					MemberUserUtils.setJIzHuFlag(LoginActivity.this,"true");
				}else{
					MemberUserUtils.setJIzHuFlag(LoginActivity.this,"false");
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		if(v.getId()==R.id.mLogin){
			if (TextUtils.isEmpty(mLoginNumber.getText().toString())) {
				ToastUtil.ShowCentre(LoginActivity.this, "请输入手机号码");
				return;
			}
			if (TextUtils.isEmpty(mLoginPswd.getText().toString())) {
				ToastUtil.ShowCentre(LoginActivity.this, "请输入登录密码");
				return;
			}

			MemberUserUtils.setPhone(this, mLoginNumber.getText().toString());
			MemberUserUtils.setPswd(this, mLoginPswd.getText().toString());

			LoginUserPost(true);
		}
		if(v.getId()==R.id.mEnterpriseQuery){
			Intent mEnterpriseQuery = new Intent(LoginActivity.this, RegisterCreatActivity.class);
			startActivity(mEnterpriseQuery);
		}
	}

	@Override
	public void initData() {
	}

	/**
	 * 用户的登录
	 * 
	 * @param isShow
	 */
	private void LoginUserPost(boolean isShow) {
		AjaxParams params = new AjaxParams();
		if(MemberUserUtils.getJIzHuFlag(this).equals("true")){
			params.put("uphone", MemberUserUtils.getPhone(this));
			params.put("upswd", MemberUserUtils.getPswd(this));
		}else{
			params.put("uphone", mLoginNumber.getText().toString());
			params.put("upswd", mLoginPswd.getText().toString());
		}
		httpPost(Consts.URL + Consts.APP.loginUser, params, Consts.actionId.resultFlag, isShow, "正在登录...");
	}

	@Override
	protected void callBackSuccess(ResponseEntry entry, int actionId) {
		super.callBackSuccess(entry, actionId);

		switch (actionId) {
		case Consts.actionId.resultFlag:

			if (null != entry.getData() && !TextUtils.isEmpty(entry.getData())) {
				userModel = mGson.fromJson(entry.getData(), UserModel.class);
				MemberUserUtils.setToken(LoginActivity.this, userModel.getUtoken());
				MemberUserUtils.setUid(LoginActivity.this, userModel.getUid());
				MemberUserUtils.setName(LoginActivity.this, userModel.getUname());
				MemberUserUtils.setLoginFlag(LoginActivity.this, userModel.getUtype());
				MemberUserUtils.putBean(LoginActivity.this, "user_messgae", userModel);

				connect(userModel.getUtoken());
			}
			break;

		}

	}

	@Override
	protected void callBackAllFailure(String strMsg, int actionId) {
		super.callBackAllFailure(strMsg, actionId);
		ToastUtil.show(LoginActivity.this, strMsg);

	}

	/**
	 * 建立与融云服务器
	 *
	 * @param token
	 */
	private void connect(String token) {


		Log.e("Pony_log", "--onTokenIncorrect");
		RongIM.connect(token, new RongIMClient.ConnectCallback() {
			@Override
			public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus code) {
				//消息数据库打开，可以进入到主页面
			}

			@Override
			public void onSuccess(String s) {

				Intent intent = new Intent(LoginActivity.this, FrameworkActivity.class);
				startActivity(intent);
				finish();
			}

			@Override
			public void onError(RongIMClient.ConnectionErrorCode errorCode) {


				Log.i("pony_log","errorCode:"+errorCode);
				if (errorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONN_TOKEN_INCORRECT)) {
					//从 APP 服务获取新 token，并重连
				} else {
					//无法连接 IM 服务器，请根据相应的错误码作出对应处理
				}
			}
		});


	}

}
